using System;
using System.Collections.Generic;
using System.Text;
using Calc.Execution;

namespace Calc.Operations
{
	public class AssignmentOperator : BinaryOperator
	{
		public override CalcResult Calc(ExecutionContext context)
		{
			if ( _leftSide is Function )
			{
				// take the existing function, and assign
				// the rights side to Operation of the function

				Function func = (Function) _leftSide;

				func.Operation = _rightSide;

				context.CreateFunction(func);
			}
			else if ( _leftSide is Variable )
			{
				// assign the resulting value of the 
				// right side to the leftside 
				Variable var = (Variable)_leftSide;

				double val = _rightSide.GetValue(context);

				context.SetVariable(var.Name, val);

				_value = val;
			}

			return new CalcResult(_value);
		}

		/// <summary>
		/// Returns the value of the right side of the assignment
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public override double GetValue(ExecutionContext context)
		{
			if ( _rightSide == null )
				throw new ArgumentNullException("RightSide", "RightSide is null, so a calculation is not possible");

			return _rightSide.GetValue(context);
		}

		public override int Precidence
		{
			get { return 0; }
		}

		public override string Symbol
		{
			get { return "="; }
		}

		public override string ToString()
		{
			string left = "";
			if ( _leftSide != null )
				left = _leftSide.ToString();

			string right = "";

			if ( _rightSide != null )
				right = _rightSide.ToString();

			return left + Symbol + right;
		}
	}
}
